package com.future.mayi.widget;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.future.baselib.utils.CommonUtils;
import com.imnjh.imagepicker.util.FileUtil;
import com.future.mayi.R;
import com.future.mayi.adapter.ApplyImgAdapter;
import com.future.mayi.dialog.CommonDialog;
import com.future.mayi.model.interfaces.ListImgListener;
import com.future.mayi.model.interfaces.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 周大虎 on 2017/9/30.
 */

public class ListImgView extends LinearLayout implements OnItemClickListener {

    RecyclerView recyclerView;
    ApplyImgAdapter adapter;
    private Context mContext;

    private int margin;
    private int itemW;
    private int maxSelectNum;
    /**
     * true为可添加可删除
     * false为只显示无添加删除
     */
    private boolean openSelect;


    private ListImgListener listener;

    public ListImgView(Context context) {
        super(context);
        init(context, null);
    }


    public ListImgView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ListImgView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }


    private void init(Context context, AttributeSet attrs) {
        mContext = context;
        View.inflate(context, R.layout.layout_list_img, this);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view_img);
        adapter = new ApplyImgAdapter(context, new ArrayList<String>());

        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ListImgView);
            maxSelectNum = typedArray.getInteger(R.styleable.ListImgView_max_select_num, 3);
            margin = typedArray.getDimensionPixelSize(R.styleable.ListImgView_item_margin, CommonUtils.dip2px(mContext, 10));
            itemW = typedArray.getDimensionPixelSize(R.styleable.ListImgView_item_width, CommonUtils.dip2px(mContext, 65));
            openSelect = typedArray.getBoolean(R.styleable.ListImgView_open_select, false);
            typedArray.recycle();
        }
        setMargin(margin == 0 ? CommonUtils.dip2px(mContext, 10) : margin);
        setItemW(itemW == 0 ? CommonUtils.dip2px(mContext, 80) : itemW);
        setOpenSelect(openSelect);
        setMaxSelectNum(maxSelectNum == 0 ? 3 : maxSelectNum);

        ViewGroup.LayoutParams layoutParams = recyclerView.getLayoutParams();
        int itemMaxItem = 4;
        int line = maxSelectNum / itemMaxItem + (maxSelectNum % itemMaxItem > 0 ? 1 : 0);
        int height = (itemW + margin) * line;
        int width = (itemW + margin) * ((maxSelectNum > itemMaxItem) ? itemMaxItem : maxSelectNum);
        layoutParams.width = width;
        layoutParams.height = height;
        adapter.setOnItemClickListener(this);
        GridLayoutManager mgr = new GridLayoutManager(mContext, (maxSelectNum > itemMaxItem) ? itemMaxItem : maxSelectNum);
        recyclerView.setLayoutManager(mgr);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setHasFixedSize(false);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 添加照片
     *
     * @param path
     */
    public void addImg(String path) {
        if (adapter == null)
            return;
        if (path == null)
            return;
        if (getMaxSelectNum() < 1) return;
        if (openSelect)
            if (adapter.getItemCount() > 0
                    && (!TextUtils.isEmpty(adapter.getItem(adapter.getItemCount() - 1)))
                    && (adapter.getItem(adapter.getItemCount() - 1).equals("default"))) {
                adapter.delete(adapter.getItemCount() - 1);
            }
        adapter.addMore(path);
        if (openSelect)
            if (getMaxSelectNum() > 0) {
                addDefaultItem();
            }
    }

    public void addImg(List<String> path) {
        if (adapter == null)
            return;
        if (path == null)
            return;
        if (getMaxSelectNum() < path.size()) return;
        if (openSelect)
            if (adapter.getItemCount() > 0
                    && (!TextUtils.isEmpty(adapter.getItem(adapter.getItemCount() - 1)))
                    && (adapter.getItem(adapter.getItemCount() - 1).equals("default"))) {
                adapter.delete(adapter.getItemCount() - 1);
            }
        adapter.addMore(path);
        if (openSelect)
            if (getMaxSelectNum() > 0) {
                addDefaultItem();
            }
    }


    /**
     * 判断是否为空
     *
     * @return
     */
    public boolean contentIsEmpty() {
        if (adapter != null && adapter.getItemCount() > 0) {
            for (int i = 0; i < adapter.getList().size(); i++) {
                String path = adapter.getList().get(i);
                if ((!TextUtils.isEmpty(path)) && (!path.equals("default")) && FileUtil.exist(path))
                    return false;
            }
        }
        return true;
    }


    /**
     * 获取照片
     *
     * @return
     */
    public List<String> getImg() {
        if (contentIsEmpty())
            return null;
        List<String> list = new ArrayList<>();
        for (int i = 0; i < adapter.getList().size(); i++) {
            String path = adapter.getList().get(i);
            if ((!TextUtils.isEmpty(path)) && (!path.equals("default")) && FileUtil.exist(path))
                list.add(path);
            if (list.size() == maxSelectNum)
                break;
        }
        return list;
    }


    /**
     * 获取 最多再能显示几张
     *
     * @return
     */
    public int getMaxSelectNum() {
        List<String> list = getImg();
        int size = maxSelectNum;

        if (list != null) {
            size = size - list.size();
            if ((!TextUtils.isEmpty(list.get(list.size() - 1))) && list.get(list.size() - 1).equals("default"))
                size = size + 1;
        }
        if (size == 0)
            size = maxSelectNum;
        return size;
    }


    /**
     * 获取所有照片的Base64
     *
     * @return
     */
    public List<String> getImgString() {
        if (contentIsEmpty())
            return null;
        List<String> stringList = new ArrayList<>(adapter.getList().size());
        for (int i = 0; i < adapter.getList().size(); i++) {
            String path = adapter.getList().get(i);
            if ((!TextUtils.isEmpty(path)) && (!path.equals("default")) && FileUtil.exist(path))
                stringList.add(path);
        }
        return stringList;
    }


    @Override
    public void OnItem(View view, final int position) {
        if (openSelect && view.getId() == R.id.iv_delete) {
            new CommonDialog.Builder(mContext)
                    .setMessage("是否删除此照片")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if (listener != null) listener.onClickDeleteImg(position);
                            adapter.delete(position);
                        }
                    }).show();
        } else if (openSelect && view.getId() == R.id.ll_default) {
            if (listener != null) listener.onClickAddImg(getMaxSelectNum());
        } else if (view.getId() == R.id.iv_img) {
            if (listener != null) listener.onClickImg(position);
        }

    }

    @Override
    public void OnLongItem(View view, int position) {

    }


    private void addDefaultItem() {
        adapter.addMore("default");
    }


    public void setMargin(int margin) {
        this.margin = margin;
        if (mContext == null) return;
        if (adapter != null) adapter.setMargin(margin);
    }

    public void setItemW(int itemW) {
        this.itemW = itemW;
        if (mContext == null) return;
        if (adapter != null) adapter.setImgHeight(itemW);
    }

    public void setOpenSelect(boolean openSelect) {
        this.openSelect = openSelect;
        if (mContext == null) return;
        if (adapter != null) adapter.setOpenSelect(openSelect);
        if (openSelect && adapter != null && adapter.getItemCount() == 0)
            addDefaultItem();
    }

    public void setMaxSelectNum(int maxSelectNum) {
        this.maxSelectNum = maxSelectNum;
        if (mContext == null) return;
        if (adapter != null) adapter.setMaxSelectNum(maxSelectNum);
    }


    public void setListener(ListImgListener listener) {
        this.listener = listener;
    }


}
